# -*- coding: utf-8 -*-
'''考虑把term封装成类，用面向对象的方式实现以下函数
'''
import time

from datetime import datetime, timedelta

from dateutil import parser

from common.utils import tz

from common.lottery.cyclical.fc3d.model.activity import Activity

from sqlalchemy import func


def calc_term_by_ts(ts):
    '''每日21:15 开奖
    '''
    prefix, start_ts = tz.get_day_and_start_ts(ts)
    max = Activity.query.order_by(Activity.term.desc()).first()
    next_term = 0

    if int(prefix[2:4]) > int(max.term[0:2]):
        next_term = '%s%s' % (prefix[2:4], '001')
    else:
        deadline_ts = start_ts + 76440 # 21:14:00

        if ts > deadline_ts:
            next_term = str(int(max.term) + 1)
        else:
            if not max.number:
                next_term = max.term
            else:
                next_term = str(int(max.term) + 1)

    return next_term


def _plus_term(day, real_term, offset):
    # day: datetime
    # real_term: int
    # offset: int
    real_term += offset

    if real_term <= 0:
        # 找去年期數
        result = Activity.query.filter(Activity.term.like(str(int(day) - 1) + '%')).order_by(Activity.term.desc()).first()
        if not result:
            real_term = '001'
        else:
            real_term = int(result.term) + real_term
            day = int(day) - 1

    return day, real_term

def plus_term(term, offset):
    '''计算期号，offset可以为负数
    '''
    if offset == 0:
        return term
    day, real_term = term[:2], int(term[2:])

    day, real_term = _plus_term(day, real_term, offset)

    return '%s%s' % (day, real_term)


def xrange_term(term, count, step=1):
    '''生成器，根据plus term生成一个迭代器，类似xrange
    '''
    if step == 0:
        raise ValueError('step must be not 0')
    if count == 0:
        yield term
    cur_count = 0
    day, real_term = term, int(term)

    while abs(cur_count) < abs(count):
        cur_count += 1
        if cur_count == 1:
            yield term
        else:
            day, real_term = _plus_term(day, real_term, step)
            yield str(real_term)


def calc_start_ts_by_term(term):
    '''通过期数计算开始时间，用来手动开启当前期数（无偏移量）
    '''
    now = tz.local_now()
    dt_now = datetime(now.year, now.month, now.day, now.hour, now.minute, now.second)
    deadline = datetime(now.year, now.month, now.day, 21, 14, 00)

    if deadline > dt_now:
        one_day_before_now = now - timedelta(days=1)
        start_ts = tz.local_datetime_to_ts('%s-%s-%s 21:15:00' % (one_day_before_now.year,
                                                                  one_day_before_now.month,
                                                                  one_day_before_now.day))
    else:
        start_ts = tz.local_datetime_to_ts('%s-%s-%s 21:15:00' % (now.year, now.month, now.day))

    return start_ts


def calc_stop_ts(start_ts):
    '''根据开始时间和当前的时间，来计算结束的时间，无偏移量
    秒數加一天，結束時間為起始時間加上一天的秒數(86400)
    '''
    term = calc_term_by_ts(start_ts)
    return calc_start_ts_by_term(term) + 86400
